<template>
  <div>
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form @submit="submit" :form="form">
        <a-form-item
          label="仿真设备"
          :labelCol="{ span: 7 }"
          :wrapperCol="{ span: 10 }"
        >
          <a-select
            v-decorator="[
              'deviceId',
              { rules: [{ required: true, message: '必须选择一个仿真设备' }] },
            ]"
          >
            <a-select-option
              v-for="item in deviceList"
              :value="item.id"
              :key="item.id"
              >{{ item.deviceName }}——{{
                item.product.productName
              }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          label="原始数据（设备推送至中继器）"
          :labelCol="{ span: 7 }"
          :wrapperCol="{ span: 10 }"
        >
          <a-input v-decorator="['rawData']" />
        </a-form-item>
        <a-form-item
          label="说点人话"
          :labelCol="{ span: 7 }"
          :wrapperCol="{ span: 10 }"
        >
          <a-input v-decorator="['toPeople']" />
        </a-form-item>
        <a-form-item
          label="格式化数据（中继器处理原始数据后推送至服务器）"
          :labelCol="{ span: 7 }"
          :wrapperCol="{ span: 10 }"
        >
          <!-- <a-input v-decorator="['formmatData']" /> -->
          <json-viewer
            :value="formmated"
            copyable
            theme="my-awesome-json-theme"
          />
        </a-form-item>
      </a-form>
    </a-card>
    <footer-tool-bar>
      <a-button type="primary" @click="createDemo" style="margin-right: 12px"
        >生成仿真数据样例</a-button
      >
      <a-button type="primary" @click="submit" style="margin-right: 12px"
        >推送当前数据</a-button
      >
      <a-button type="primary" @click="submit2" style="margin-right: 12px"
        >随机生成并推送数据</a-button
      >      
      <a-button type="primary" @click="autoSubmit" style="margin-right: 12px"
        >开始自动推送(5s)</a-button
      >  
      <a-button type="primary" @click="stopAutoSubmit" style="margin-right: 12px"
        >停止自动推送</a-button
      >
    </footer-tool-bar>
  </div>
</template>

<script>
import FooterToolBar from "@/components/tool/FooterToolBar";
import JsonViewer from "vue-json-viewer";
import { devicePage, deviceDetail } from "@/services/device";
import { pushDeviceData } from "@/services/deviceData";

export default {
  name: "BasicForm",
  components: { FooterToolBar, JsonViewer },
  data() {
    return {
      form: this.$form.createForm(this),
      value: 1,
      deviceList: [],
      formmated: {},
      timer: null
    };
  },
  mounted() {
    this.queryDevicePage();
  },
  methods: {
    autoSubmit() {
      if (this.timer == null) {
        this.timer = setInterval(this.submit2,5000)
      }
    },
    stopAutoSubmit() {
      clearInterval(this.timer)
      this.timer = null
    },
    submit2() {
      this.createDemo();
      this.submit();
    },
    submit() {
      if (this.formmated.length == 0) {
        this.$message.success("无数据");
      } else {
        pushDeviceData(this.formmated).then((rep) => {
          if (rep.data.success) {
            this.$message.success("推送数据成功");
          } else {
            this.$message.error(rep.data.msg);
          }
        });
      }
    },
    createDemo() {
      this.form.validateFields((err, values) => {
        console.log(values);
        deviceDetail(values.deviceId).then((rep) => {
          var data = rep.data.data;
          var product = data.product;

          var rawData = "";
          var formmatData = [];
          var toPeople = "";
          var dataBase = product.dataBase;

          // start flag
          if (product.dataStartFlag != null) {
            rawData = rawData + product.dataStartFlag;
          }
          // mid data
          product.productDataList.forEach((item) => {
            var size = item.endPos - item.startPos + 1;
            if (dataBase === 10) {
              var max = Math.pow(10, size) - 1;
              var a = Math.random();
              var res = Math.floor((max + 1 - 0) * a + 0);
              res = this.fixXStart(res, size, "0");
              rawData = rawData + res;

              toPeople =
                toPeople +
                item.dataName +
                ": " +
                res +
                " " +
                item.dataUnit +
                "; ";
            }
          });
          // end flag
          if (product.dataEndFlag != null) {
            rawData = rawData + product.dataEndFlag;
          }

          formmatData = {
            tenantId: data.tenantId,
            deviceIp: data.ipAddr,
            rawData: rawData,
          };

          if (!err) {
            this.form.setFieldsValue({
              rawData: rawData,
              toPeople: toPeople,
            });
          }
          this.formmated = formmatData;
        });
      });
    },
    fixXStart(str, n, x) {
      return (Array(n).join(x) + str).slice(-n);
    },
    queryDevicePage() {
      devicePage({ entity: { status: 1 } }).then((rep) => {
        this.deviceList = rep.data.data.records;
      });
    },
  },
  computed: {
    desc() {
      return this.$t("pageDesc");
    },
  },
};
</script>

<style scoped>
</style>
